package edu.hrbu.trade01.controller;

import edu.hrbu.trade01.util.R;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static edu.hrbu.trade01.util.ConstUtil.*;

/**
 * @author 徐登宇
 */
@RestController
@RequestMapping("/file")
public class FileController {

    // 重构：上传图片都走这个
    @RequestMapping("/upload/{type}")
    public R upload(MultipartFile file, @PathVariable("type") String type) {
        String uploadFileName = file.getOriginalFilename();
        String path = "E:/Java/codes/a_hxy/hxy-trade/trade-01/src/main/resources/static";
        String picPath = "/web/pic/";

        if (PIC_FIRM.equals(type)) {
            picPath=picPath+type; // 这个要存进数据库
        } else if (PIC_COMMENCE.equals(type)) {
            picPath=picPath+type;
        }

        path = path + picPath;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        try {
            file.transferTo(new File(path + "/" + uploadFileName));
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail();
        }
        picPath = picPath + "/" + uploadFileName;
        return R.ok(picPath);

    }

}
